<?php
#
# UNLVSpatial: a dmBridge module for spatial content
#
# Copyright © 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class UNLVSpatialIndexer {

	/** @var array of DMObjects */
	private $indexed_objects = array();
	/** @var array of DMObjects */
	private $skipped_objects = array();

	/**
	 * @return array Array of DMObjects
	 */
	public function getIndexedObjects() {
		return $this->indexed_objects;
	}

	/**
	 * @return array Array of DMObjects
	 */
	public function getSkippedObjects() {
		return $this->skipped_objects;
	}

	/**
	 * @param DMCollection collection The collection to index.
	 * @param DMDCElement field The field to index.
	 */
	public function reindex(DMCollection $collection, DMDCElement $field) {
		$this->reset();

		$ds = UNLVSpatial::getDataStore();
		$ds->deleteAllObjectsInCollection($collection);

		$num_objects = $collection->getNumObjects();
		$results_per_page = 1000;

		$query = new DMObjectQuery();
		$query->addCollection($collection);
		$query->setNumResultsPerPage($results_per_page);
		for ($i = 1; $i <= $num_objects; $i = $i + $results_per_page) {
			$query->setPage($i);
			$results = $query->getSearchResults();
			foreach ($results as $obj) {
				try {
					UNLVSpatialObjectFactory::spatializeObject($obj);
					$obj->getSpatialDataSource();
					$ds->updateObject($obj);
					$this->indexed_objects[] = $obj;
				} catch (Exception $e) {
					// boundary units are unsupported
					$this->skipped_objects[] = $obj;
				}
			}
		}
	}

	private function reset() {
		
		$this->indexed_objects = array();
		$this->skipped_objects = array();
	}

}

